<?php
namespace addon\wechat_config\logic;
// +----------------------------------------------------------------------
// | Author: xiaojun <920668625@qq.com>
// +----------------------------------------------------------------------
use app\common\logic\LogicBase;
use think\Db;
use \tpfcore\Core;
use addon\wechat_fans\logic\WechatFans;
use addon\wechat_qrcode\logic\WechatQrcode;
use addon\wechat_material\logic\WechatMaterial;
use tpfcore\web\Curl;
class ReceiveEvent extends LogicBase
{
	public function receiveEventFunc($object){
		$content = '';
        switch ($object->Event)
        {
            case 'subscribe':
                $openid = $object->FromUserName;
                try{
                    $access_token = WechatFunc::getAccessToken();
                    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
                    $res = json_decode(Curl::get($url));
                    
                    $data['openid']=$res->openid;
                    $data['nickname']=$res->nickname;
                    $data['headimg']=$res->headimgurl;

                    $user_model=Core::loadAddonModel("User");
                    $list_user=$user_model->getOneObject(["openid"=>$res->openid],"id");

                    if(!empty($list_user)){
                        $data['id']=$list_user['id'];
                    }
                    /*
                        如果是直接关注的，没有EventKey，直接写入用户表
                        否则是通过带参数的二维码过来的，用户推广（推荐）过来的，写入用户表，并记录关系
                    */
                    if(empty($object->EventKey)){
                        $content="欢迎使用头泉科技公众号";
                    }
                    else{

                        $data['parent_id'] = str_replace('qrscene_','',(string)$object->EventKey);

                        $listParent=$user_model->getOneObject(["id"=>$data['parent_id']],"nickname");

                        if(empty($listParent)){
                            $content="欢迎使用头泉科技公众号";
                        }
                        else{
                            $content="欢迎使用头泉科技公众号,你的上级是".$listParent['nickname'];
                        }
                        
                    }

                    $user_model->saveObject($data);    //有就更新，没有就添加

                } catch (\Exception $e) {
                    $content = "获取用户信息失败";
                }
                break;
            case 'unsubscribe':

                (new WechatFans())->unsubscribeFans($object);

                break;
            case 'CLICK':

                switch ($object->EventKey) {
                    case 'COMPANY':
                        $content = array();
                        $content[] = [
                            'Title'=>WECHAT_NAME,
                            'Description'=>'',
                            'PicUrl'=>'http://www.tpframe.com/icon/cartoon.jpg',
                            'Url'=>'http://www.tpframe.com'
                        ];
                        break;
                    default:
                        $content = self::helpReplyMsgFunc($object,false);
                        if(empty($content)){
                            $content = '无相关消息';
                        }
                        break;
                }
                
                break;
            case 'VIEW':

                $content = '跳转链接 '.$object->EventKey;
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'SCAN':
                // 之前关注过的用户
                $openid = $object->FromUserName;
                try{
                    $access_token = WechatFunc::getAccessToken();
                    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid";
                    $res = json_decode(Curl::get($url));

                    $data['openid']=$res->openid;
                    $data['nickname']=$res->nickname;
                    $data['headimg']=$res->headimgurl;

                    $user_model=Core::loadAddonModel("User");
                    $list_user=$user_model->getOneObject(["openid"=>$res->openid],"id");

                    if(!empty($list_user)){
                        $data['id']=$list_user['id'];
                    }

                    /*
                        如果已经注册了的，就不管
                        如果未注册，用户推广（推荐）过来的，写入用户表，并记录关系
                    */
                    if(empty($list_user) && $object->EventKey){
                        $data['parent_id'] =$object->EventKey;
                        $listParent=$user_model->getOneObject(["id"=>$data['parent_id']],"nickname");
                        if(empty($listParent)){
                            $content="欢迎使用头泉科技公众号";
                        }
                        else{
                            $content="欢迎使用头泉科技公众号,你的上级是".$listParent['nickname'];
                        }
                        $user_model->saveObject($data);
                    }
                    else{
                        $content = "你已注册，赶快使用头泉科技享受便捷的服务吧！";
                    }
                } catch (\Exception $e) {
                    $content = "获取用户信息失败";
                }
                break;
            case 'LOCATION':
                $data = [
                    'openid'=>(string)$object->FromUserName,
                    'Location_X'=>$object->Latitude,//纬度
                    'Location_Y'=>$object->Longitude//经度
                ];
                Db::name('WechatFansLocation')->insert($data);
                $content = '上传位置：纬度 '.$object->Latitude.';经度 '.$object->Longitude;
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'scancode_waitmsg':

                if ($object->ScanCodeInfo->ScanType == 'qrcode'){
                    $content = '扫码带提示：类型 二维码 结果：'.$object->ScanCodeInfo->ScanResult;
                }else if ($object->ScanCodeInfo->ScanType == 'barcode'){
                    $codeinfo = explode(',',strval($object->ScanCodeInfo->ScanResult));
                    $codeValue = $codeinfo[1];
                    $content = '扫码带提示：类型 条形码 结果：'.$codeValue;
                }else{
                    $content = '扫码带提示：类型 '.$object->ScanCodeInfo->ScanType.' 结果：'.$object->ScanCodeInfo->ScanResult;
                }
                break;
            case 'scancode_push':

                $content = '扫码推事件';
                $content .= '时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'pic_sysphoto':

                $content = '系统拍照';
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'pic_weixin':

                $content = '相册发图：数量 '.$object->SendPicsInfo->Count;
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'pic_photo_or_album':

                $content = '拍照或者相册：数量 '.$object->SendPicsInfo->Count;
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            case 'location_select':

                $content = '发送位置：标签 '.$object->SendLocationInfo->Label;
                $content .= ' 时间：'.date('Y-m-d H:i:s')."\n";
                break;
            default:
            
                $content = 'receive a new event: '.$object->Event;
                break;
        }

        return WechatReceive::DisposeContent($object,$content);
	}



    protected function subscribeFunc($object){
        $content = array();
        switch(WECHAT_SUBSCRIBE_MSG_TYPE){

            case 'text':
                $content = strip_tags(WECHAT_SUBSCRIBE_MSG_TEXT,'<a>');
                preg_match_all('/\[([0-9a-z_]+)\]/i',$content,$matches);
                foreach($matches[1] as $emoji){
                    $Emoji   = WechatFunc::getEemoj($emoji);
                    //处理表情
                    $content = str_replace('['.$emoji.']',WechatFunc::bytesToEmoji($Emoji['utf16']),$content);
                }
                if(!empty($object->EventKey)){
                    $content .= "\n来自二维码场景 ".str_replace('qrscene_','',$object->EventKey);
                }
                break;
            case 'image':
                $data = (new WechatMaterial())->getImageMaterialByMediaId(WECHAT_SUBSCRIBE_MSG_VALUE);
                $content = ['MsgType'=>'image','MediaId'=>$data['media_id']];
                break;
            case 'voice':
                $data = (new WechatMaterial())->getVoiceMaterialByMediaId(WECHAT_SUBSCRIBE_MSG_VALUE);
                $content = [
                    'MsgType'=>'voice',
                    'Title'=>$data['name'],
                    'Description'=>'来自：'.WECHAT_NAME,
                    'MusicUrl'=>WechatFunc::format_url($data['local_url']),
                    'HQMusicUrl'=>WechatFunc::format_url($data['local_url'])
                ];
                break;
            case 'video':
                $data = (new WechatMaterial())->getVideoMaterialByMediaId(WECHAT_SUBSCRIBE_MSG_VALUE);
                $content = [
                    'MsgType'=>'video',
                    'MediaId'=>$data['media_id'],
                    'ThumbMediaId'=>'',
                    'Title'=>$data['name'],
                    'Description'=>$data['description']
                ];
                break;
            case 'news':
                $WechatMaterial = new WechatMaterial();
                $data    = $WechatMaterial->getNewsMaterialByMediaId(WECHAT_SUBSCRIBE_MSG_VALUE);
                $content = array();
                $content[] = [
                    'MsgType'=>'news',
                    'Title'=>$data['title'],
                    'Description'=>$data['description'],
                    'PicUrl'=>WechatFunc::format_url($data['pic_url']),
                    'Url'=>$data['url']?$data['url']:$data['content_source_url']
                ];
                $son_data = $WechatMaterial->newsMaterialList(['group_id'=>$data['id']],0,'id asc');
                foreach ($son_data as $key => $value) {
                    $content[] = [
                        'MsgType'=>'news',
                        'Title'=>$value['title'],
                        'Description'=>$value['description'],
                        'PicUrl'=>WechatFunc::format_url($value['pic_url']),
                        'Url'=>$value['url']?$value['url']:$value['content_source_url']
                    ];
                }
                break;
            default:
                break;
        }

        return $content;
    }

    protected function helpReplyMsgFunc($object,$is_auto = true){
        $content   = array();
        $replydata = WechatReceive::materialKeywordList(trim($object->EventKey));
        if($replydata){

            switch(WECHAT_REPLY_TYPE)
            {
                case 'image':
                    $content = array();
                    $content = ['MsgType'=>'image','MediaId'=>$replydata['media_id']];
                    break;
                case 'voice':
                    $content = array();
                    $content = [
                        'MsgType'     => 'voice',
                        'Title'       => $replydata['name'],
                        'Description' => '来自：'.WECHAT_NAME,
                        'MusicUrl'    => WechatFunc::format_url($replydata['local_url']),
                        'HQMusicUrl'  => WechatFunc::format_url($replydata['local_url'])
                    ];
                    break;
                case 'video':
                    $content = array();
                    $content = [
                        'MsgType'      => 'video',
                        'MediaId'      => $replydata['media_id'],
                        'ThumbMediaId' => '',
                        'Title'        => $replydata['name'],
                        'Description'  => $replydata['description']
                    ];
                    break;
                case 'news':
                    $content = array();
                    $content[] = [
                        'MsgType'     => 'news',
                        'Title'       => $replydata['title'],
                        'Description' => $replydata['description'],
                        'PicUrl'      => WechatFunc::format_url($replydata['pic_url']),
                        'Url'         => $replydata['url']?$replydata['url']:$replydata['content_source_url']
                    ];
                    $son_data = (new WechatMaterial())->newsMaterialList(['group_id'=>$replydata['id']],0,'id asc');
                    foreach ($son_data as $key => $value) {
                        $content[] = [
                            'MsgType'     => 'news',
                            'Title'       => $value['title'],
                            'Description' => $value['description'],
                            'PicUrl'      => WechatFunc::format_url($value['pic_url']),
                            'Url'         => $value['url']?$value['url']:$value['content_source_url']
                        ];
                    }
                    break;
                case 'text':
                    $content = '';
                    $content = strip_tags($replydata,'<a>');

                    preg_match_all('/\[([0-9a-z_]+)\]/i',$content,$matches);
                    foreach($matches[1] as $emoji){
                        $info    = WechatFunc::getEemoj($emoji);
                        //处理表情
                        $content = str_replace('['.$emoji.']',WechatFunc::bytesToEmoji($info['utf16']),$content);
                    }
                break;
            }
        }else if($is_auto){

            //自动回复模式
            defined('WECHAT_ROBOT_ON') or define('WECHAT_ROBOT_ON',false);
            if (WECHAT_ROBOT_ON)
            {
                $content = WechatRobot::tuling($keyword);
            }else{
                //默认回复内容
                switch(WECHAT_AUTO_MSG_TYPE)
                {
                    case 'image':
                        $content = array();
                        $content = ['MsgType'=>'image','MediaId'=>WECHAT_AUTO_MSG_VALUE];
                        break;
                    case 'voice':
                        $info = (new WechatMaterial())->getVoiceMaterialByMediaId(WECHAT_AUTO_MSG_VALUE);

                        $content = array();
                        $content = [
                            'MsgType'     => 'voice',
                            'Title'       => $info['name'],
                            'Description' => '来自：'.WECHAT_NAME,
                            'MusicUrl'    => WechatFunc::format_url($info['local_url']),
                            'HQMusicUrl'  => WechatFunc::format_url($info['local_url'])
                        ];
                        break;
                    case 'video':
                        $info = (new WechatMaterial())->getVideoMaterialByMediaId(WECHAT_AUTO_MSG_VALUE);
                        $content = array();
                        $content = [
                            'MsgType'      => 'video',
                            'MediaId'      => WECHAT_AUTO_MSG_VALUE,
                            'ThumbMediaId' => '',
                            'Title'        => $info['name'],
                            'Description'  => $info['description']
                        ];
                        break;
                    case 'news':
                        $info    = (new WechatMaterial())->getNewsMaterialByMediaId(WECHAT_AUTO_MSG_VALUE);
                        $content = array();
                        $content[] = [
                            'MsgType'     => 'news',
                            'Title'       => $info['title'],
                            'Description' => $info['description'],
                            'PicUrl'      => WechatFunc::format_url($info['pic_url']),
                            'Url'         => $info['url']?$info['url']:$info['content_source_url']
                        ];

                        $son_data = (new WechatMaterial())->newsMaterialList(['group_id'=>$info['id']],0,'id asc');
                        foreach ($son_data as $key => $value) {
                            $content[] = [
                                'MsgType'     => 'news',
                                'Title'       => $value['title'],
                                'Description' => $value['description'],
                                'PicUrl'      => WechatFunc::format_url($value['pic_url']),
                                'Url'         => $value['url']?$value['url']:$value['content_source_url']
                            ];
                        }
                        break;
                    case 'text':
                        $content = '';
                        $content = strip_tags(WECHAT_AUTO_MSG_TEXT,'<a>');
                        preg_match_all('/\[([0-9a-z_]+)\]/i',$content,$matches);
                        foreach($matches[1] as $emoji)
                        {
                            $info    = WechatFunc::getEemoj($emoji);
                            $content = str_replace('['.$emoji.']',WechatFunc::bytesToEmoji($info['utf16']),$content);
                        }
                        break;
                }
            }
        }
        return $content;
    }
}